import React, { useEffect, useRef } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import './App.css'
import { updateState, addTodo, getTodos } from './store/actions/todos'
import { RootState } from './store'
function App () {
  const dispatch = useDispatch()
  const refInput = useRef<HTMLInputElement>(null)
  useEffect(() => {
    dispatch(getTodos())
  }, [dispatch])
  // useSelector
  // 看函数的签名

  // const todos = useSelector<{todos:{id:number, name:string, isDone:boolean}[]}, {id:number, name:string, isDone:boolean}[]>(state => { return state.todos })
  // const todos = useSelector((state: {todos: {id:number, name:string, isDone:boolean}[]}) => { return state.todos })
  const todos = useSelector((state: RootState) => { return state.todos })
  const update = (id: number) => {
    dispatch(updateState(id))

    // dispatch({
    //   type: 'xxx',
    //   payload: 1
    // })
  }
  const add = () => {
    if (refInput.current) {
      dispatch(addTodo(refInput.current.value))
    }
  }
  const keyUp = (e:React.KeyboardEvent<HTMLInputElement>) => {
    console.log(e)
    if (e.code === 'Enter') {
      const t = e.target as HTMLInputElement
      dispatch(addTodo(t.value))

      // if('value' in e.target) {
      //   console.log(e.target.value )
      // }
    }
  }
  return (
    <div className="App">
      <h1>todos</h1>
      <div>
        <input ref={refInput} onKeyUp={keyUp}/><button onClick={ add }>add</button>
      </div>
      <ul>
        {todos.map(it => (<li key={it.id}>{it.name}, {it.isDone ? '完成了' : '未完成'}
          <button onClick={() => { update(it.id) } }>切换状态</button></li>))}
      </ul>
    </div>
  )
}

export default App
